package com.heihx.interceptor;

import com.heihx.constant.JwtClaimsConstant;
import com.heihx.context.BaseContext;
import com.heihx.properties.JwtProperties;
import com.heihx.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * jwt令牌校验拦截器
 */
@Component
@Slf4j
public class JwtTokenAdminInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 校验jwt令牌
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)){
            //拦截到的不是动态方法，放行
            return true;
        }

        String token = request.getHeader(jwtProperties.getAdminTokenName());

        //校验令牌
        try{
            log.info("校验令牌:{}",token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
            Long empid = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());
            log.info("当前员工:{}",empid);
            BaseContext.setCurrentId(empid);
            return true;
        }catch (Exception e){
            response.setStatus(401);
            return false;
        }
    }
}
